/*
 * @Author: [wcy]
 * @Date: 2021-12-06 13:43:58
 * @LastEditors: [wcy]
 * @LastEditTime: 2021-12-15 18:07:42
 * @Description: 
 */
// pages/cart/index.js
import {
  showModal,showToast
} from "../../utils/asyncWx.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  onLoad() {

  },
  onShow() {
    // 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    // 获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || [];
    this.setData({
      address
    })
    this.setCart(cart);
  },
  // 收货地址
  handleChooseAddress() {
    wx.chooseAddress({
      success: (res) => {
        console.log(res);
        let address = res;
        address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo
        wx.setStorageSync("address", address);
      },
    });

  },
  // 商品选中
  handleItemChange(e) {
    // 获取被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    // 获取购物车数组
    let {
      cart
    } = this.data;
    // 找到被修改的商品对象
    let index = cart.findIndex(v => v.goods_id === goods_id)
    // 选中 状态取反
    cart[index].checked = !cart[index].checked
    // 把购物车数据重新设置会data中的缓存中
    this.setCart(cart);
  },
  // 设置购物车状态的同时 重新计算底部工具栏的数据
  setCart(cart) {
    let allChecked = true;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price;
        totalNum += v.num;
      } else {
        allChecked = false
      }
    })
    allChecked = cart.length != 0 ? allChecked : false
    this.setData({
      cart,
      totalPrice,
      totalNum,
      allChecked
    });
    wx.setStorageSync("cart", cart)
  },
  // 商品全选功能
  handleItemAllCheck() {
    // 获取data中的数据
    let {
      cart,
      allChecked
    } = this.data;
    // 修改值
    allChecked = !allChecked;
    // 循坏修改cart数组中的商品选中状态
    cart.forEach(v => v.checked = allChecked);
    // 把修改后的值重新填充回data或缓存中
    this.setCart(cart)

  },
  // 商品数量
  async handleItemNumEdit(e) {

    // 获取传递过来的参数
    const {
      operation,
      id
    } = e.currentTarget.dataset;
    // 获取购物车数组
    let {
      cart
    } = this.data;
    // 找到要修改的商品的索引
    const index = cart.findIndex(v => v.goods_id === id);
    if (cart[index].num === 1 && operation === -1) {
      // 弹窗提示
      const res = await showModal({
        content: "您是否想要删除？"
      });
      if (res.confirm) {
        cart.splice(index, 1)
        this.setCart(cart)
      }
    } else {
      cart[index].num += operation;
      this.setCart(cart);
    }
  },
  // 点击结算
  async handlePay(){
    // 判断是否有收货地址
    const {address,totalNum}=this.data;
    if (!address.userName) {
      await showToast({title:"您还没有选择收货地址"});
      return;
    }
    // 判断用户有没有选购商品
    if (totalNum===0) {
      await showToast({title:"您还没有选购商品"});
      return;
    }
    // 跳转到支付页面
    wx.navigateTo({
      url: '/pages/pay/index',
    });
  },
  

})